<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    

    <meta name="baidu-site-verification" content="lt822VnP06" />
    <meta name="baidu-site-verification" content="0Ajixw1Puk" />
    <meta name="google-site-verification" content="gCQD0Y6f0YlPTZTAjp_mqms4C7TlkMWrg3Xy0mFdMwI" />
    <title>使用基于注解的mybatis时,利用反射和注解生成sql语句 | Giraffe&#39;s Home</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="在开发时遇到一个问题，在使用基于注解的mybatis插入一个对象到mysql时，在写sql语句时需要列出对象的所有属性，所以在插入一个拥有10个以上属性的对象时sql语句就会变得很长，写起来也很不方便,也很容易拼错。google了一下也没有找到什么解决方式(可能是姿势不对😜)，在stackoverflow上提的问题截止目前还没有人回答。所以自己想了一个基于反射和注解的解决办法git地址：">
<meta property="og:type" content="article">
<meta property="og:title" content="使用基于注解的mybatis时,利用反射和注解生成sql语句">
<meta property="og:url" content="http://yemengying.com/2015/10/28/基于注解的mybatis插入对象时利用反射生成sql语句/index.html">
<meta property="og:site_name" content="Giraffe's Home">
<meta property="og:description" content="在开发时遇到一个问题，在使用基于注解的mybatis插入一个对象到mysql时，在写sql语句时需要列出对象的所有属性，所以在插入一个拥有10个以上属性的对象时sql语句就会变得很长，写起来也很不方便,也很容易拼错。google了一下也没有找到什么解决方式(可能是姿势不对😜)，在stackoverflow上提的问题截止目前还没有人回答。所以自己想了一个基于反射和注解的解决办法git地址：">
<meta property="og:image" content="https://pic.yupoo.com/jiananshi/f6f7ed31/6940bad0.jpg">
<meta property="og:updated_time" content="2018-12-14T09:23:55.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用基于注解的mybatis时,利用反射和注解生成sql语句">
<meta name="twitter:description" content="在开发时遇到一个问题，在使用基于注解的mybatis插入一个对象到mysql时，在写sql语句时需要列出对象的所有属性，所以在插入一个拥有10个以上属性的对象时sql语句就会变得很长，写起来也很不方便,也很容易拼错。google了一下也没有找到什么解决方式(可能是姿势不对😜)，在stackoverflow上提的问题截止目前还没有人回答。所以自己想了一个基于反射和注解的解决办法git地址：">
<meta name="twitter:image" content="https://pic.yupoo.com/jiananshi/f6f7ed31/6940bad0.jpg">
    

    

    
        <link rel="icon" href="https://yemengying.com/qiniu/image/image/favicon.png" />
    


    <link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/lib/open-sans/styles.css">
    <link rel="stylesheet" href="/lib/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/lib/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/lib/fancybox/jquery.fancybox.css">
    
    
        <script type="text/javascript">
(function(i,s,o,g,r,a,m) {i['GoogleAnalyticsObject']=r;i[r]=i[r]||function() {
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-75861791-1', 'auto');
ga('send', 'pageview');

</script>
    
    
    
        <script>
var _hmt = _hmt || [];
(function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?44bb8bfb1a576270255713e37746eb82";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();
</script>

    

</head>
<body>
    <script src="//github.elemecdn.com/jiananshi/req/0.1.0/lib/req.js"></script>
    <script src="//npm.elemecdn.com/jinkela@1.2.18/umd.js"></script>
    <script src="//github.elemecdn.com/jiananshi/DisqusJS/2.0.8/index.js"></script>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">Giraffe&#39;s Home</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">归档</a>
                
                    <a class="main-nav-link" href="/categories">分类</a>
                
                    <a class="main-nav-link" href="/tags">标签</a>
                
                    <a class="main-nav-link" href="/about">关于</a>
                
                    <a class="main-nav-link" href="/message">留言</a>
                
                    <a class="main-nav-link" href="/friends">友链</a>
                
                    <a class="main-nav-link" href="/reading">正在读...</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="https://pic.yupoo.com/jiananshi/e85e4303/735cf286.jpeg" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/.">首页</a></td>
                
                    <td><a class="main-nav-link" href="/archives">归档</a></td>
                
                    <td><a class="main-nav-link" href="/categories">分类</a></td>
                
                    <td><a class="main-nav-link" href="/tags">标签</a></td>
                
                    <td><a class="main-nav-link" href="/about">关于</a></td>
                
                    <td><a class="main-nav-link" href="/message">留言</a></td>
                
                    <td><a class="main-nav-link" href="/friends">友链</a></td>
                
                    <td><a class="main-nav-link" href="/reading">正在读...</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="https://pic.yupoo.com/jiananshi/e85e4303/735cf286.jpeg" />
            <h2 id="name">Giraffe</h2>
            <h3 id="title">Java Developer</h3>
            <span id="location"><i class="fa fa-map-marker"></i>Shanghai, China</span>
            <a id="follow" target="_blank" href="https://github.com/giraffe0813/">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                56
                <span>文章</span>
            </div>
            <div class="article-info-block">
                36
                <span>标签</span>
            </div>
        </div>
        <div class="profile-block recent-comments">
            <p class="recent-comments-title">最新评论</p>
            <ul id="disqus-recent-comments" class="recent-comments-container">
            </ul>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/giraffe0813" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/atom.xml" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="2015/10/28/基于注解的mybatis插入对象时利用反射生成sql语句/" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            使用基于注解的mybatis时,利用反射和注解生成sql语句
        </h1>
    

                <div class="article-meta">
                    
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/2015/10/28/基于注解的mybatis插入对象时利用反射生成sql语句/">
            <time datetime="2015-10-28T05:21:29.000Z" itemprop="datePublished">2015-10-28</time>
        </a>
    </div>


                    
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/java/">java</a>
    </div>

                    
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/annotation/">annotation</a>, <a class="tag-link" href="/tags/java/">java</a>, <a class="tag-link" href="/tags/mybatis/">mybatis</a>, <a class="tag-link" href="/tags/reflection/">reflection</a>
    </div>

                </div>
            </header>
        
        <div class="article-entry" itemprop="articleBody">
        
            
                <div id="toc" class="toc-article">
                <strong class="toc-title">文章目录</strong>
                    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#第一版-利用反射"><span class="toc-number">1.</span> <span class="toc-text">第一版(利用反射)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#最终版-加入注解"><span class="toc-number">2.</span> <span class="toc-text">最终版(加入注解)</span></a></li></ol>
                </div>
            
            <blockquote>
<p>在开发时遇到一个问题，在使用基于注解的mybatis插入一个对象到mysql时，在写sql语句时需要列出对象的所有属性，所以在插入一个拥有10个以上属性的对象时sql语句就会变得很长，写起来也很不方便,也很容易拼错。google了一下也没有找到什么解决方式(可能是姿势不对😜)，在stackoverflow上提的<a href="http://stackoverflow.com/questions/33383134/how-to-insert-an-objectmore-than-10-properties-into-mysql-via-mybatis-based-on" target="_blank" rel="external">问题</a>截止目前还没有人回答。所以自己想了一个基于反射和注解的解决办法<br>git地址：<div id="badge-container-giraffe0813-spring-mybatis-utils-a555c91" class="hexo-github" style="width: 100%"></div>
<script src="/hexo-github/badge.js"></script>
<script type="text/javascript">
  loadStyle("/hexo-github/style.css");
  loadStyle("/hexo-github/octicons/octicons.css");
  new Badge("#badge-container-giraffe0813-spring-mybatis-utils-a555c91", "giraffe0813", "spring-mybatis-utils", "a555c91", false);
</script>
</p>
</blockquote>
<a id="more"></a>
<p>下面是之前的代码片段:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Insert</span>(<span class="string">"insert into poi_shop(name,brand,tags,status,phone,mobile,business_time,address,city,lng,lat,business_type,attribute_json) values(#&#123;name&#125;,#&#123;brand&#125;,#&#123;tags&#125;,#&#123;status&#125;,#&#123;phone&#125;,#&#123;mobile&#125;,#&#123;business_time&#125;,#&#123;address&#125;,#&#123;city&#125;,#&#123;lng&#125;,#&#123;lat&#125;,#&#123;business_type&#125;,#&#123;attribute_json&#125;)"</span>)</div><div class="line"><span class="meta">@Options</span>(useGeneratedKeys = <span class="keyword">true</span>, keyProperty = <span class="string">"id"</span>, keyColumn = <span class="string">"id"</span>)</div><div class="line"><span class="function"><span class="keyword">public</span> Long <span class="title">insertPoiInfo</span><span class="params">(PoiBo poiBo)</span></span>;</div></pre></td></tr></table></figure>
<p>是不是too looooooooooooong：</p>
<p><img src="https://pic.yupoo.com/jiananshi/f6f7ed31/6940bad0.jpg" alt="image"></p>
<h3 id="第一版-利用反射"><a href="#第一版-利用反射" class="headerlink" title="第一版(利用反射)"></a>第一版(利用反射)</h3><p>首先想到的是可以利用反射获得对象的所有属性，然后拼接成sql语句。所以写了一个基于反射拼装sql语句的方法，然后基于mybatis动态获得sql语句的方式 获得完整的sql 具体的代码如下:<br>接口层改为下面的样子，sql语句的生成放到PoiSqlProvider的insertPoiBo方法中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@InsertProvider</span>(type = PoiSqlProvider.class, method = <span class="string">"insertPoiBo"</span>)</div><div class="line"><span class="function"><span class="keyword">public</span> Long <span class="title">insertPoiInfo</span><span class="params">(@Param(<span class="string">"poiBo"</span>)</span>PoiBo poiBo)</span>;</div></pre></td></tr></table></figure>
<p>PoiSqlProvider.class</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">insertPoiBo</span><span class="params">(Map&lt;String,Object&gt; map)</span></span>&#123;</div><div class="line">       PoiBo poiBo = (PoiBo)map.get(<span class="string">"poiBo"</span>);</div><div class="line">       StringBuilder sql = <span class="keyword">new</span> StringBuilder(<span class="string">"insert into poi_shop "</span>);</div><div class="line">       <span class="comment">//get sql via reflection</span></div><div class="line">       Map&lt;String,String&gt; sqlMap = getAllPropertiesForSql(poiBo, <span class="string">"poiBo"</span>);</div><div class="line">       <span class="comment">//</span></div><div class="line">       sql.append(sqlMap.get(<span class="string">"field"</span>)).append(sqlMap.get(<span class="string">"value"</span>));</div><div class="line">       System.out.println(sql.toString());</div><div class="line">       <span class="keyword">return</span> sql.toString();</div><div class="line"></div><div class="line">   &#125;</div><div class="line"></div><div class="line"><span class="comment">//根据传入的对象 基于反射生成两部分sql语句</span></div><div class="line">   <span class="function"><span class="keyword">private</span>  Map&lt;String,String&gt; <span class="title">getAllPropertiesForSql</span><span class="params">(Object obj, String objName)</span></span>&#123;</div><div class="line"></div><div class="line">       Map&lt;String,String&gt; map = <span class="keyword">new</span> HashMap&lt;String,String&gt;();</div><div class="line">        <span class="keyword">if</span>(<span class="keyword">null</span> == obj) <span class="keyword">return</span> map;</div><div class="line">       StringBuilder filedSql = <span class="keyword">new</span> StringBuilder(<span class="string">"("</span>);</div><div class="line">       StringBuilder valueSql = <span class="keyword">new</span> StringBuilder(<span class="string">"value ("</span>);</div><div class="line">       Field[] fields = obj.getClass().getDeclaredFields();</div><div class="line">       <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; fields.length; i++) &#123;</div><div class="line">           filedSql.append(fields[i].getName() + <span class="string">","</span>);</div><div class="line">           valueSql.append(<span class="string">"#&#123;"</span> + objName + <span class="string">"."</span> + fields[i].getName() + <span class="string">"&#125;,"</span>);</div><div class="line">       &#125;</div><div class="line"></div><div class="line">       <span class="comment">//remove last ','</span></div><div class="line">       valueSql.deleteCharAt(valueSql.length() - <span class="number">1</span>);</div><div class="line">       filedSql.deleteCharAt(filedSql.length() - <span class="number">1</span>);</div><div class="line">       valueSql.append(<span class="string">") "</span>);</div><div class="line">       filedSql.append(<span class="string">") "</span>);</div><div class="line">       map.put(<span class="string">"field"</span>,filedSql.toString());</div><div class="line">       map.put(<span class="string">"value"</span>, valueSql.toString());</div><div class="line"></div><div class="line">       System.out.println(<span class="string">"database filed sql: "</span> + filedSql.toString());</div><div class="line">       System.out.println(<span class="string">"value sql:"</span> + valueSql.toString());</div><div class="line"></div><div class="line">       <span class="keyword">return</span> map;</div><div class="line">   &#125;</div></pre></td></tr></table></figure>
<p>下面是基于反射生成的两部分sq语句和最后拼接的语句</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">database filed sql:</div><div class="line"> </div><div class="line">(id,name,brand,tags,status,phone,mobile,business_time,address,city,lng,lat,business_type,attribute_json,updated_at,created_at)</div><div class="line"> </div><div class="line">value sql:</div><div class="line"></div><div class="line">value(#&#123;poiBo.id&#125;,#&#123;poiBo.name&#125;,#&#123;poiBo.brand&#125;,#&#123;poiBo.tags&#125;,#&#123;poiBo.status&#125;,#&#123;poiBo.phone&#125;,#&#123;poiBo.mobile&#125;,#&#123;poiBo.business_time&#125;,#&#123;poiBo.address&#125;,#&#123;poiBo.city&#125;,#&#123;poiBo.lng&#125;,#&#123;poiBo.lat&#125;,#&#123;poiBo.business_type&#125;,#&#123;poiBo.attribute_json&#125;,#&#123;poiBo.updated_at&#125;,#&#123;poiBo.created_at&#125;) </div><div class="line"></div><div class="line">insert into poi_shop (id,name,brand,tags,status,phone,mobile,business_time,address,city,lng,lat,business_type,attribute_json,updated_at,created_at) value (#&#123;poiBo.id&#125;,#&#123;poiBo.name&#125;,#&#123;poiBo.brand&#125;,#&#123;poiBo.tags&#125;,#&#123;poiBo.status&#125;,#&#123;poiBo.phone&#125;,#&#123;poiBo.mobile&#125;,#&#123;poiBo.business_time&#125;,#&#123;poiBo.address&#125;,#&#123;poiBo.city&#125;,#&#123;poiBo.lng&#125;,#&#123;poiBo.lat&#125;,#&#123;poiBo.business_type&#125;,#&#123;poiBo.attribute_json&#125;,#&#123;poiBo.updated_at&#125;,#&#123;poiBo.created_at&#125;)</div></pre></td></tr></table></figure>
<p>要注意的是如果数据库的字段名和插入对象的属性名不一致，那么不能使用生成的database filed sql。</p>
<h3 id="最终版-加入注解"><a href="#最终版-加入注解" class="headerlink" title="最终版(加入注解)"></a>最终版(加入注解)</h3><p>上面的getAllPropertiesForSql方法有个缺点，如果数据库的字段名和类的属性名不一致，就不能依靠反射获得sql了。所以借鉴老大的ORM框架也写了一个注解Column，用于model类的属性上，表明属性所对应数据库字段。下面是Column注解的snippet。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> java.lang.annotation.ElementType;</div><div class="line"><span class="keyword">import</span> java.lang.annotation.Retention;</div><div class="line"><span class="keyword">import</span> java.lang.annotation.RetentionPolicy;</div><div class="line"><span class="keyword">import</span> java.lang.annotation.Target;</div><div class="line"></div><div class="line"><span class="comment">/* 定义字段的注解*/</span></div><div class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</div><div class="line"><span class="comment">/*该注解只能用在成员变量上*/</span></div><div class="line"><span class="meta">@Target</span>(ElementType.FIELD)</div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Column &#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 用来存放字段的名字 如果未指定列名，默认列名使用成员变量名</div><div class="line">     *</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function">String <span class="title">name</span><span class="params">()</span> <span class="keyword">default</span> ""</span>;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p>之后在model类属性上加入对应的注解,省略getter和setter。Column的name为空时，代表属性名和字段名一致。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PoiBo</span> </span>&#123;</div><div class="line"></div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> Long id;</div><div class="line">	<span class="meta">@Column</span>(name = <span class="string">"poi_name"</span>)</div><div class="line">	<span class="keyword">private</span> String name;<span class="comment">//表示name属性对应数据库poi_name字段</span></div><div class="line">	<span class="meta">@Column</span>(name = <span class="string">"poi_brand"</span>)</div><div class="line">	<span class="keyword">private</span> String brand;<span class="comment">//表示brand属性对应数据库poi_brand字段</span></div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> String tags;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> Integer status;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> String phone;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> String mobile;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> String business_time;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> Float average_price;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> String address;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> String city;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> Double lng;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> Double lat;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> String business_type;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> String attribute_json;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> Timestamp updated_at;</div><div class="line">	<span class="meta">@Column</span></div><div class="line">	<span class="keyword">private</span> Timestamp created_at;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p>修改getAllPropertiesForSql方法，通过获取类属性上的注解获得数据库字段名。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span>  Map&lt;String,String&gt; <span class="title">getAllPropertiesForSql</span><span class="params">(Object obj, String objName)</span></span>&#123;</div><div class="line"></div><div class="line">        Map&lt;String,String&gt; map = <span class="keyword">new</span> HashMap&lt;String,String&gt;();</div><div class="line">         <span class="keyword">if</span>(<span class="keyword">null</span> == obj) <span class="keyword">return</span> map;</div><div class="line">        StringBuilder filedSql = <span class="keyword">new</span> StringBuilder(<span class="string">"("</span>);</div><div class="line">        StringBuilder valueSql = <span class="keyword">new</span> StringBuilder(<span class="string">"value ("</span>);</div><div class="line">        Field[] fields = obj.getClass().getDeclaredFields();</div><div class="line">        <span class="keyword">for</span> (Field field : fields) &#123;</div><div class="line">                <span class="comment">// 判断该成员变量上是不是存在Column类型的注解</span></div><div class="line">                <span class="keyword">if</span> (!field.isAnnotationPresent(Column.class)) &#123;</div><div class="line">                    <span class="keyword">continue</span>;</div><div class="line">                &#125;</div><div class="line"></div><div class="line">                Column c = field.getAnnotation(Column.class);<span class="comment">// 获取实例</span></div><div class="line">                <span class="comment">// 获取元素值</span></div><div class="line">                String columnName = c.name();</div><div class="line">                <span class="comment">// 如果未指定列名，默认列名使用成员变量名</span></div><div class="line">                <span class="keyword">if</span> (<span class="string">""</span>.equals(columnName.trim())) &#123;</div><div class="line">                    columnName = field.getName();</div><div class="line">                &#125;</div><div class="line"></div><div class="line">            filedSql.append(columnName + <span class="string">","</span>);</div><div class="line">            valueSql.append(<span class="string">"#&#123;"</span> + objName + <span class="string">"."</span> + field.getName() + <span class="string">"&#125;,"</span>);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">//remove last ','</span></div><div class="line">        valueSql.deleteCharAt(valueSql.length() - <span class="number">1</span>);</div><div class="line">        filedSql.deleteCharAt(filedSql.length() - <span class="number">1</span>);</div><div class="line">        valueSql.append(<span class="string">") "</span>);</div><div class="line">        filedSql.append(<span class="string">") "</span>);</div><div class="line">        map.put(<span class="string">"field"</span>,filedSql.toString());</div><div class="line">        map.put(<span class="string">"value"</span>, valueSql.toString());</div><div class="line"></div><div class="line">        System.out.println(<span class="string">"database filed sql: "</span> + filedSql.toString());</div><div class="line">        System.out.println(<span class="string">"value sql:"</span> + valueSql.toString());</div><div class="line"></div><div class="line">        <span class="keyword">return</span> map;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">`</div></pre></td></tr></table></figure>
<p>利用反射+注解之后的输出结果，可以看到sql语句正确按照name的Column注解的输出了name属性对应的数据库字段是poi_name.</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">database filed sql: </div><div class="line"></div><div class="line">(id,poi_name,poi_brand,tags,status,phone,mobile,business_time,average_price,address,city,lng,lat,business_type,attribute_json,updated_at,created_at) </div><div class="line"></div><div class="line">value sql:</div><div class="line">value(#&#123;poiBo.id&#125;,#&#123;poiBo.name&#125;,#&#123;poiBo.brand&#125;,#&#123;poiBo.tags&#125;,#&#123;poiBo.status&#125;,#&#123;poiBo.phone&#125;,#&#123;poiBo.mobile&#125;,#&#123;poiBo.business_time&#125;,#&#123;poiBo.average_price&#125;,#&#123;poiBo.address&#125;,#&#123;poiBo.city&#125;,#&#123;poiBo.lng&#125;,#&#123;poiBo.lat&#125;,#&#123;poiBo.business_type&#125;,#&#123;poiBo.attribute_json&#125;,#&#123;poiBo.updated_at&#125;,#&#123;poiBo.created_at&#125;) </div><div class="line"></div><div class="line">insert into poi_shop </div><div class="line">(id,poi_name,poi_brand,tags,status,phone,mobile,business_time,average_price,address,city,lng,lat,business_type,attribute_json,updated_at,created_at) value (#&#123;poiBo.id&#125;,#&#123;poiBo.name&#125;,#&#123;poiBo.brand&#125;,#&#123;poiBo.tags&#125;,#&#123;poiBo.status&#125;,#&#123;poiBo.phone&#125;,#&#123;poiBo.mobile&#125;,#&#123;poiBo.business_time&#125;,#&#123;poiBo.average_price&#125;,#&#123;poiBo.address&#125;,#&#123;poiBo.city&#125;,#&#123;poiBo.lng&#125;,#&#123;poiBo.lat&#125;,#&#123;poiBo.business_type&#125;,#&#123;poiBo.attribute_json&#125;,#&#123;poiBo.updated_at&#125;,#&#123;poiBo.created_at&#125;)</div></pre></td></tr></table></figure>
<p>写的好累放张萌图吧</p>
<p><img src="https://pic.yupoo.com/jiananshi/74a79838/7a6c1fc1.jpg" alt="cat"></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://yemengying.com/2015/10/28/基于注解的mybatis插入对象时利用反射生成sql语句/" data-id="cjtvbucji0040z15sipyqizmp" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    
        <a href="http://yemengying.com/2015/10/28/基于注解的mybatis插入对象时利用反射生成sql语句/#comments" class="article-comment-link disqus-comment-count" data-disqus-url="http://yemengying.com/2015/10/28/基于注解的mybatis插入对象时利用反射生成sql语句/">评论</a>
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/2015/10/29/译-以生产者消费者为例阐述如何使用wait，notify和notifyAll/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    【译】以生产者消费者为例阐述如何使用wait，notify和notifyAll
                
            </div>
        </a>
    
    
        <a href="/2015/10/26/译-如何重置一个ArrayList-clear-vs-removeAll/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">【译】如何重置一个ArrayList--clear vs removeAll</div>
        </a>
    
</nav>


    
    <script>
   DisqusJS.getArticleComments();
   </script>
</article>


    
    <section id="comments">
    
        
    <div id="disqus_thread">
        <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>

    
    </section>

</section>
            
        </div>
        <footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2019 Mengying Ye<br>
            Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
        </div>
    </div>
</footer>
        
    
   <script>
   DisqusJS.getRecentComments(document.querySelector('#disqus-recent-comments'));
   </script>



    
        <script src="/lib/fancybox/jquery.fancybox.pack.js"></script>
    


<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>
